package sim.ring.technical.comms;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Vector;

public class SerialReader implements Runnable {
	private InputStream in;
	private Vector<EventListenerInterface> listeners = new Vector<EventListenerInterface>();
    
    public SerialReader (InputStream in) {
    	this.in = in;
    }
    
    public SerialReader (InputStream in, EventListenerInterface listener) {
    	this.in = in;
    	listeners.add(listener);
    }
    
    
    public synchronized void addEventListener(EventListenerInterface listener) {
    	listeners.add(listener);
    }
    
    public synchronized void removeEventListener(EventListenerInterface listener) {
    	listeners.remove(listener);
    }
    
    public void run() {
    	byte[] buffer = new byte[1];
    	int len=-1;
    	try {
    		while ((len=this.in.read(buffer)) > -1) {
    			if (len>0) {
    				SerialEvent event = new SerialEvent(this, new String(buffer,0,1));
    				Iterator<EventListenerInterface> it = listeners.iterator();
        			while (it.hasNext()) {
        				it.next().handle(event);
        			}
    			}
    		}
    	} catch (IOException e) {
    		e.printStackTrace();
    	}            
    }
}